//
//  HEGoodsDetailsViewController.m
//  HealthElderly
//
//  Created by 吴欧 on 2020/10/20.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEGoodsDetailsViewController.h"
#import "HEGoodDetailsHeaderView.h"
#import "HEGoodDetailsTitleCell.h"
#import "HEGoodsModel.h"
#import "UIGoodsDetailsRefuseCell.h"
#import "HEGoodDetailsSpecCell.h"
#import "SelectSpecView.h"
#import "HEGoodsDetailsModel.h"
#import "HECommentsHeaderCell.h"
#import "HEGoodsDetailsCommentsCell.h"
#import "HEGoodsCommentModel.h"
#import "HEGoodsDetailsFooterView.h"
#import "HEGoodsDetailsCompanyCell.h"
#import "HEAddCartRequest.h"
#import "HECartViewController.h"
#import "HECreateOrderViewController.h"
#import "HECommentsViewController.h"

static NSString * const CellTitleId = @"HEGoodDetailsTitleCell";
static NSString * const CellRefuseId = @"UIGoodsDetailsRefuseCell";
static NSString * const CellSpecId = @"HEGoodDetailsSpecCell";
static NSString * const CellCommentHeadId = @"HEGoodsDetailsCommentsCell";
static NSString * const CellCommentId = @"HEGoodsDetailsCommentsCell";


@interface HEGoodsDetailsViewController ()<UITableViewDelegate, UITableViewDataSource, HEGoodsDetailsTabBarDelegate>

@property (nonatomic, strong) GDTableView *tableView;

@property (nonatomic, strong) UIButton *backBtn;

@property (nonatomic, strong) UIButton *realBackBtn;

@property (nonatomic, strong) HEGoodsModel *goods;
@property (nonatomic, strong) HEGoodsDetailsModel *details;
@property (nonatomic, strong) HEGoodDetailsHeaderView *headView;
@property (nonatomic, strong) SelectSpecView *seleView;
@property (nonatomic, strong) NSString *noticStr;

@property (nonatomic, strong) HEGoodsDetailsTabBar *tabbar;

@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) NSMutableArray <HEGoodsCommentModel *> *commentsArr;

@property (nonatomic, strong) HEAddCartRequest *skuModel;

@property (nonatomic, strong) NSMutableArray <HEGoodsModel *> * recomGoodsArr;

// 创建一个全局的group
@property (nonatomic, strong) dispatch_group_t group;


@end

@implementation HEGoodsDetailsViewController

- (NSMutableArray<HEGoodsModel *> *)recomGoodsArr {
    if (!_recomGoodsArr) {
        _recomGoodsArr = [NSMutableArray array];
    }
    return _recomGoodsArr;
}

- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (HEGoodsDetailsModel *)details {
    if (!_details) {
        _details = [HEGoodsDetailsModel new];
    }
    return _details;
}

- (NSMutableArray<HEGoodsCommentModel *> *)commentsArr {
    if (!_commentsArr) {
        _commentsArr = [NSMutableArray array];
    }
    return _commentsArr;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jumpGoodDetailsNotification:) name:KNotificationToGoodsDetails object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 防止重复跳转
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KNotificationToGoodsDetails object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.hidden = YES;
    self.view.backgroundColor = KWhiteColor;
    [self zx_removeNavGradientBac];

    //设置导航栏背景色RGB中Alpha为0
    self.zx_navBarBackgroundColorAlpha = 0;
    
    //隐藏分割线
    self.zx_navLineView.hidden = YES;
    // 隐藏默认返回按钮
    [self.zx_navLeftBtn removeFromSuperview];

    _skuModel = [HEAddCartRequest new];

    [self setUpNav];
    
    [self initUI];
    
    [self loadData];
}

- (void)jumpGoodDetailsNotification:(NSNotification *)notfi {
    if (nil != notfi.object) {
        HEGoodsModel *obj = (HEGoodsModel *)notfi.object;
        
        HEGoodsDetailsViewController *vc = [HEGoodsDetailsViewController new];
        vc.goodsId = obj.id;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma marke - load Data
- (void)loadData {
    __weak typeof(self) weakself = self;

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        weakself.group = dispatch_group_create();
        [weakself loadDetailsData];
        [weakself loadCommentData];

        //因上面请求中有加入dispatch_group_enter 和 dispatch_group_leave,所以真正等待上面线程执行完才执行这里面的请求
        dispatch_group_notify(weakself.group, queue, ^{
            dispatch_main_async_safe(^{
                [weakself initCell];
            })
        });
    });
 
}

- (void)loadDetailsData {
    dispatch_group_enter(_group);

    __weak typeof(self) weakself = self;
   [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:KGoodsDetails parameters:@{@"id": [NSNumber numberWithLong:_goodsId]} success:^(id  _Nonnull responseObject) {
       
       NSLog(@"response：  %@", [responseObject mj_JSONString]);

        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        self.details = [HEGoodsDetailsModel mj_objectWithKeyValues:response.data];
        self.headView.model = self.details.goods.goods;
       
       self.tabbar.isFavorite = self.details.favorite;
       self.tabbar.goods = self.details.goods.goods;
       self.tabbar.showCart = self.details.goods.goods.channel != HEChannelTypeSpinalReh
       && self.details.goods.goods.channel != HEChannelTypeHomeCare;
       self.tabbar.barType = self.details.goods.goods.visit ? HEGoodsDetailsTabBarTypeAppointment : HEGoodsDetailsTabBarTypeOnlyBuy;

 
        NSMutableArray *attrs = [NSMutableArray array];
        for (HEProductattributevalueModel *model in self.details.goods.productAttributeValueList) {
            [attrs addObject:model.name];
        }
        self.formModel.specStr = [NSString stringWithFormat:@"请选择：%@", [attrs componentsJoinedByString:@","]];
       
       if (self.details.goods.goods.channel == HEChannelTypeHomeCare ) {
           [self loadListData];
       }
 
       dispatch_group_leave(weakself.group);

    } failure:^(NSError * _Nonnull error) {
        dispatch_group_leave(weakself.group);
    }];
}

- (void)loadCommentData {
    dispatch_group_enter(_group);
    __weak typeof(self) weakself = self;

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@1 forKey:@"pageNum"];
    [params setObject:@2 forKey:@"pageSize"];
    [params setObject:[NSNumber numberWithLong:_goodsId] forKey:@"goodsId"];

    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:KGoodsDetailsConsultList parameters:params success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        MallData *commentData = [MallData mj_objectWithKeyValues:response.data[@"list"]];
        
        [self.commentsArr addObjectsFromArray:[HEGoodsCommentModel mj_objectArrayWithKeyValuesArray:commentData.records]];
        self.formModel.dg_commnetsTotal = commentData.total;
        
        dispatch_group_leave(weakself.group);
    } failure:^(NSError * _Nonnull error) {
        dispatch_group_leave(weakself.group);
    }];
}

- (void)loadListData {
    dispatch_group_enter(_group);
    __weak typeof(self) weakself = self;

    HEPageRequest *request = [HEPageRequest new];
    request.pageNum = 1;
    request.pageSize = 999;
    [request addParmas:@"1036025" key:@"product_category_id"];
    [request addParmas:[NSString stringWithFormat:@"%ld", self.details.goods.goods.storeId] key:@"store_id"];
//    [request addParmas:[NSNumber numberWithInteger:self.details.goods.goods.productCategoryId] key:@"product_category_id"];

    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KstoreProducts parameters:request success:^(id  _Nonnull responseObject) {
        HEPageResponse *response = [HEPageResponse mj_objectWithKeyValues:responseObject];
        [self.recomGoodsArr addObjectsFromArray:[HEGoodsModel mj_objectArrayWithKeyValuesArray:response.data.list]];
        
        self.formModel.recomGoodsArr = self.recomGoodsArr;
        dispatch_group_leave(weakself.group);

     } failure:^(NSError * _Nonnull error) {
         dispatch_group_leave(weakself.group);
    }];
}

- (void)initCell {
    
    // 总段
    _sections = [NSMutableArray array];
    
    NSMutableArray *classArr = [NSMutableArray array];

    // 标题
    GDFiterCellModel *titleModel = [GDFiterCellModel new];
    titleModel.cellType = GDFiterCellTypeGoodsDetailsTitle;
    self.formModel.goodsModel = _details.goods.goods;
    self.formModel.storeModel = _details.goods.storeInfo;
    
    // 退款
    GDFiterCellModel *refuseModel = [GDFiterCellModel new];
    refuseModel.cellType = GDFiterCellTypeGoodsDetailsRefuse;
    refuseModel.registType = GDFiterCellRegisterByXib;
    
    // 规格
    GDFiterCellModel *skuModel = [GDFiterCellModel new];
    skuModel.cellType = GDFiterCellTypeGoodsDetailsSku;
    skuModel.registType = GDFiterCellRegisterByXib;
    skuModel.cellDisplayType = self.details.goods.productAttributeValueList.count > 0 ? GDCellDisplayShow: GDCellDisplayNone;

    // 用户评论头部视图
    GDFiterCellModel *commentHeadModel = [GDFiterCellModel new];
    commentHeadModel.cellType = GDFiterCellTypeGoodsDetailsCommentHeader;
    commentHeadModel.registType = GDFiterCellRegisterByXib;
    
    // 无用户评论
    GDFiterCellModel *noCommentModel = [GDFiterCellModel new];
    noCommentModel.cellType = GDFiterCellTypeGoodsDetailsNoComments;
    noCommentModel.registType = GDFiterCellRegisterByXib;
    noCommentModel.cellDisplayType = self.commentsArr.count > 0 ? GDCellDisplayNone: GDCellDisplayShow;
    
    // 用户评论cell
    GDFiterCellModel *commentModel = [GDFiterCellModel new];
    commentModel.cellType = GDFiterCellTypeGoodsDetailsComment;
    commentModel.cellDisplayType = self.commentsArr.count > 0 ? GDCellDisplayShow: GDCellDisplayNone;
    self.formModel.dg_commnets = self.commentsArr;
    
    self.formModel.urls = @[
    ];
    
    /*
     ,@"http://ww2.sinaimg.cn/thumbnail/677febf5gw1erma104rhyj20k03dz16y.jpg"
     @"http://ww3.sinaimg.cn/thumbnail/8e88b0c1gw1e9lpr1xydcj20gy0o9q6s.jpg",
     @"http://ww2.sinaimg.cn/thumbnail/8e88b0c1gw1e9lpr39ht9j20gy0o6q74.jpg",
     @"http://ww3.sinaimg.cn/thumbnail/8e88b0c1gw1e9lpr3xvtlj20gy0obadv.jpg",
     @"http://ww2.sinaimg.cn/bmiddle/642beb18gw1ep3629gfm0g206o050b2a.gif"
     
     */
    
    // 商品详请html
    GDFiterCellModel *detailHtmlModel = [GDFiterCellModel new];
    detailHtmlModel.cellType = GDFiterCellTypeGoodsDetailsHtml;
    
    // 公司信息
    GDFiterCellModel *companyModel = [GDFiterCellModel new];
    companyModel.cellType = GDFiterCellTypeGoodsDetailsCompany;
    companyModel.cellDisplayType = self.details.goods.goods.channel == HEChannelTypeSpinalReh ||
    self.details.goods.goods.channel == HEChannelTypeHomeCare ? GDCellDisplayShow:GDCellDisplayNone;
//    companyModel.cellDisplayType = GDCellDisplayNone;

    // 服务区域信息
    GDFiterCellModel *areaModel = [GDFiterCellModel new];
    areaModel.cellType = GDFiterCellTypeGoodsDetailsArea;
//    areaModel.cellDisplayType = GDCellDisplayNone;
    areaModel.cellDisplayType = self.details.goods.goods.visit ? GDCellDisplayShow:GDCellDisplayNone;

    // 相关推荐
    GDFiterCellModel *recomModel = [GDFiterCellModel new];
    recomModel.cellType = GDFiterCellTypeGoodsDetailsRecom;
    recomModel.cellDisplayType = self.details.goods.goods.channel == HEChannelTypeHomeCare ? GDCellDisplayShow:GDCellDisplayNone;
//    recomModel.cellDisplayType = GDCellDisplayNone;


    // 添加的时候注意顺序，暂未对顺序做处理
    classArr = @[titleModel, refuseModel, areaModel,companyModel, recomModel, skuModel, commentHeadModel, noCommentModel,commentModel, detailHtmlModel].mutableCopy;
    
    for (GDFiterCellModel *model in classArr) {
         NSMutableArray *secs = [NSMutableArray array];
         
        // 隐藏未达到条件的cell
         if (model.cellDisplayType == GDCellDisplayNone) {
             continue;
         }
        else if (model.cellType == GDFiterCellTypeGoodsDetailsComment) {
            for (HEGoodsCommentModel *comment in self.commentsArr) {
                [secs addObject:model];
            }
        }else {
            [secs addObject:model];
        }
         
        [_sections addObject: secs];
     }
    
    [self.tableView mc_registerCellByFiterModels:classArr];
    [_tableView reloadData];
    
    [self initFooterView];

}
 

- (void)setUpNav {
    
    UIView *nav = [[UIView alloc] init];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:IMAGE_NAMED(@"back_white") forState:UIControlStateNormal];
    backBtn.layer.masksToBounds = YES;
    backBtn.layer.cornerRadius = 17.5;
    backBtn.backgroundColor = [UIColor colorWithRed:58/255.0 green:58/255.0 blue:58/255.0 alpha:0.3];
    [nav addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nav).mas_offset(15);
        make.bottom.equalTo(nav).mas_offset(-10);
        make.size.mas_offset(CGSizeMake(35, 35));
    }];
//    [backBtn setImageEdgeInsets:UIEdgeInsetsMake(5,5,5,5)];
    _backBtn = backBtn;
    
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *realBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [realBackBtn setImage:IMAGE_NAMED(@"back_black") forState:UIControlStateNormal];
    [nav addSubview:realBackBtn];
    [realBackBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nav).mas_offset(15);
        make.bottom.equalTo(nav).mas_offset(-10);
        make.size.mas_offset(CGSizeMake(35, 35));
    }];
    realBackBtn.alpha = 0;
//    [realBackBtn setImageEdgeInsets:UIEdgeInsetsMake(5,5,5,5)];
    [realBackBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];

    _realBackBtn = realBackBtn;

    [self zx_addCustomNavBar:nav];
    
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 设置导航栏为白色
- (void)setLightNav{
    //显示分割线
    self.zx_navLineView.hidden = YES;
    //设置状态栏为白色
    self.zx_navStatusBarStyle = ZXNavStatusBarStyleDefault;
}

#pragma mark 设置导航栏为黑色
- (void)setDarkNav{
    //隐藏分割线
    self.zx_navLineView.hidden = NO;
    //设置状态栏为黑色
    self.zx_navStatusBarStyle = ZXNavStatusBarStyleDefault;
}

- (void)initUI {
    
    CGFloat tabbarHeight = 49 + KSafeTabbarHeight;
    
    _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight- tabbarHeight) style:UITableViewStylePlain];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.scrollsToTop = YES;
    _tableView.tableFooterView = [[UIView alloc] init];
    
    self.tableView.backgroundColor = CViewBgColor;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    HEGoodDetailsHeaderView *headView = [[HEGoodDetailsHeaderView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 300)];
    self.tableView.tableHeaderView = headView;
    _headView = headView;
    
    HEGoodsDetailsTabBar *tabbar = [[HEGoodsDetailsTabBar alloc] init];
    tabbar.delegate = self;
    _tabbar = tabbar;
    tabbar.barType = _barType;
    [self.view addSubview:tabbar];
    [tabbar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_offset(tabbarHeight);
        make.bottom.equalTo(self.view.mas_bottom);
        make.left.right.equalTo(self.view);
    }];
}

- (void)initFooterView {
    HEGoodsDetailsFooterView *footerView = [[HEGoodsDetailsFooterView alloc] initWithFrame:CGRectMake(0, KScreenHeight, KScreenWidth, 0)];
    _tableView.tableFooterView = footerView;
    [footerView getFooterViewHeightBlock:^(CGFloat height) {
        footerView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, height);
        [self.tableView reloadData];
    }];
    
    [footerView didSelectItemAtFooterView:^(HEGoodsModel * _Nonnull model) {
        HEGoodsDetailsViewController *vc = [[HEGoodsDetailsViewController alloc] init];
        vc.goodsId = model.id;
        [self.navigationController pushViewController:vc animated:YES];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableArray *sec = _sections[section];
    return sec.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    
    UITableViewCell *cell = [_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, self.formModel, indexPath);
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    if (fiterModel.cellType == GDFiterCellTypeGoodsDetailsRecom) {
        return 250;
    }
    return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
               [cell refreshContent:fiterModel formModel:self.formModel indexPath:indexPath];
    }];
}


#pragma mark -
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    CGFloat offsetY = scrollView.contentOffset.y;
   
    CGFloat sd = 180;
    
    CGFloat alpha = (sd - offsetY) / sd;
    if (alpha < 0) {
        alpha = 0;
    }

    _backBtn.alpha = alpha;
    _realBackBtn.alpha = 1-alpha;

    [self zx_setNavTransparentGradientsWithScrollView:scrollView fullChangeHeight:200 changeLimitNavAlphe:0.8 transparentGradientsTransparentBlock:^{
        [self setLightNav];
    } transparentGradientsOpaqueBlock:^{
        [self setDarkNav];
    }];
}


//核心方法
- (void)changeColorWithOffsetY:(CGFloat)offsetY {

     CGFloat sd = 180;
     
    // 计算透明度，180为随意设置的偏移量临界值
     CGFloat alpha = offsetY / sd > 1.0f ? 1 : (offsetY / sd);
 
     //导航栏主题 title文字属性
     UINavigationBar *navBar = self.navigationController.navigationBar;
     UIColor *changColor = [KWhiteColor colorWithAlphaComponent:alpha];
    
      //导航栏背景图  设置一个颜色并转化为图片
      [navBar setBackgroundImage:[UIImage imageWithColor: changColor] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
     [navBar setBarTintColor: changColor];
     [navBar setTintColor:CNavBgFontColor];
     [navBar setTitleTextAttributes:@{NSForegroundColorAttributeName :CNavBgFontColor, NSFontAttributeName : [UIFont systemFontOfSize:18]}];

    self.navigationController.navigationBar.translucent = alpha >= 1.0f ? NO : YES;
}
 

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    NSMutableArray *sec = _sections[section];
    GDFiterCellModel *fiterModel = sec.lastObject;
    
    if (fiterModel.cellType == GDFiterCellTypeGoodsDetailsTitle ||
        fiterModel.cellType == GDFiterCellTypeGoodsDetailsComment ||
        fiterModel.cellType == GDFiterCellTypeGoodsDetailsNoComments) {
        return CGFLOAT_MIN;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = CViewBgColor;
    return v;
}

 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    if (fiterModel.cellType == GDFiterCellTypeGoodsDetailsSku) {
        [self.seleView show:SpecSelectTypeBuyNow];
    }else if (fiterModel.cellType == GDFiterCellTypeGoodsDetailsCommentHeader) {
        HECommentsViewController *vc = [HECommentsViewController new];
        vc.goodsId = self.goodsId;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
 
#pragma mark -
- (SelectSpecView *)seleView {
    if (!_seleView) {
        NSMutableArray *allSepec = [NSMutableArray array];
        NSMutableArray *compareSepec = [NSMutableArray array];

        // 所有选择的组合列表
        for (HESkuStockModel *compareModel in _details.goods.skuStockList) {
            compareSepecModel *compareM = [[compareSepecModel alloc]init];
            compareM.goodspriceid = compareModel.id;
            compareM.spec_price = compareModel.price;
            compareM.spec_pic = compareModel.pic;
            compareM.stock = compareModel.stock;
            compareM.matchStr = compareModel.meno;
            [compareSepec addObject:compareM];
        }

        for (HEProductattributevalueModel *attr in _details.goods.productAttributeValueList) {
            SepecModel *sepecM = [[SepecModel alloc]init];
            sepecM.id_sepec = attr.id;
            sepecM.name_sepec = attr.name;
            [allSepec addObject:sepecM]; // 所有属性
            
          NSMutableArray *allSepeclist = [NSMutableArray array];
            for (NSString *subSpec in attr.pics) {
                SepecDetailModel *sepecmodel = [[SepecDetailModel alloc] initWithName:subSpec font:DYFont(15)];
                [allSepeclist addObject:sepecmodel]; // 属性下的规格
            }
            sepecM.arr_sepec = allSepeclist;
        }
        
        SelectSpecView *seleView = [SelectSpecView selectSpecViewWithdataArr:allSepec];
        seleView.goods = _details.goods.goods;
        seleView.comparedataArr = compareSepec;
        seleView.actionBtnBlock = ^(NSInteger skuid, NSString *price, NSInteger num, NSString *sepec) {
            // 加入购物车
            if(seleView.type == SpecSelectTypeAddCart) {
                self.skuModel = [HEAddCartRequest new];
                self.skuModel.skuId = skuid;
                self.skuModel.goodsId = self.goodsId;
                self.skuModel.total = num;
                [self addCartRequest];
            }else if (seleView.type == SpecSelectTypeBuyNow) {
               // 立即购买
                HECreateOrderViewController *vc = [HECreateOrderViewController new];
                vc.previewType = HESubmitPreviewTypeByGoodsDetails;
                vc.previewModel.total = num;
                vc.previewModel.goodsId = self.goodsId;
                vc.previewModel.type = 1;
                vc.previewModel.skuId = skuid;
                vc.goods = self.details.goods.goods;
                [self.navigationController pushViewController:vc animated:YES];
            }
        };
        seleView.finishSelectedBlock = ^(NSInteger skuid, NSString *price, NSInteger num,NSString *sepec){
            self.formModel.specStr = [NSString stringWithFormat:@"已选择：%@",sepec];
            [self.tableView reloadData];
        };
        seleView.inCompleteBlock =  ^(NSInteger skuid, NSString * price, NSInteger num,NSString *sepec){
            self.formModel.specStr = [NSString stringWithFormat:@"请选择：%@",sepec];
            [self.tableView reloadData];
        };
        
        _seleView = seleView;
    }
    
    return _seleView;
}

- (void)viewDidDisappear:(BOOL)animated {
  
}

- (void)addCartRequest {
    
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KaddCart parameters:self.skuModel success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [Dialog toast:@"添加成功" delay:2.0];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}


#pragma mark - HEGoodsDetailsTabBarDelegate

-(void)addCartHandler {
    [self.seleView show:SpecSelectTypeAddCart];
}

- (void)buyNowHandler {
    [self.seleView show:SpecSelectTypeBuyNow];
}

- (void)toCartPageHandler {
    HECartViewController *vc = [HECartViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
